'use strict';

const Controller = require('egg').Controller;
const ms = require('ms');
var Parameter = require('parameter');
var parameter = new Parameter({
  validateRoot: true, // restrict the being validate value must be a object
});
const path = require('path');
const fs=require('fs')
const sendToWormhole = require('stream-wormhole');
//故名思意 异步二进制 写入流
const awaitWriteStream = require('await-stream-ready').write;
const md5 = require('md5');
const createRule = {
  username: {
    type: 'email',
  },
  password: {
    type: 'password'
  },
};
class HomeController extends Controller {
  async index() {
    //this.ctx.app 获取app 
    //app.cache 也可以
    //对于继承controller service 也可用this.app  
    //ctx.isIOS 是插件添加的
    console.log(this.config.env,this.ctx.isIOS)
    var t=this.ctx.query.name || 'star'
    //this.ctx.body = {name:t}
    await this.ctx.render('index.html');
    //this.ctx.redirect('new')
  }
  //curl -X POST http://127.0.0.1:7001/create --data 'username=abc@abc.com&password=111111&re-password=111111'
  async create(ctx){
    console.log(ctx.request.body,ctx.validate);
    // 如果校验报错，会抛出异常
    try{
      ctx.validate(createRule,ctx.request.body);
      ctx.body = ctx.request.body;
    }catch(err){
      ctx.body=err.errors
    }
   
    //var errors = parameter.validate(ctx.request.body,createRule);
    // if(errors){
    //   ctx.body=errors;
    //   return ;
    // }  
    
  }
  async cache(ctx){
    ctx.body={data:Math.random()*33};
  }
  async getcache(ctx){
    ctx.body={cache:this.app.cache,user:this.app.user}
  }
  async addcount(ctx){
    let count = ctx.cookies.get('count');
    count = count ? Number(count) : 0;
    ctx.cookies.set('count', ++count);
    ctx.body = count;
  }
  async removecount(ctx){
    ctx.cookies.set('count', null);
    ctx.status = 204;
  }
  async setsession(ctx){
    // let count=ctx.session.count || 0;
    // ctx.session.count=++count;
    // ctx.body=ctx.session.count
    //ctx.set('Access-Control-Allow-Origin', 'http://localhost:8041');
    
    ctx.set('Access-Control-Allow-Credentials',true)
    ctx.session.user={errorCode:0,data:{name:'star',random:Math.random()}}
    ctx.body=ctx.session.user;
    // 如果用户勾选了 `记住我`，设置 30 天的过期时间
    if (0) ctx.session.maxAge = ms('30d');
  }
  async getsession(ctx){
    console.log(ctx.session.user);
    ctx.body=ctx.session.user;
  }
  async upload(ctx){
    const stream = await ctx.getFileStream();
    let newname=new Date().getTime()+Math.floor(Math.random()*10000);
    const name = '/public/upload/' + newname+path.extname(stream.filename);
    var t=path.join(__dirname,'..',name)
    console.log(t)
    var w=fs.createWriteStream(t)
    try{
      await awaitWriteStream(stream.pipe(w));
    }catch(err){
      //如果出现错误，关闭管道
      await sendToWormhole(stream);
      ctx.body=err;
    }
    ctx.body={
      url:name
    } 
  }
  async uploads(ctx){
    console.log(ctx.request.body)
    // const parts = ctx.multipart({autoFields: true });
    // let part;
    // while((part=await parts())!=null){
    //   if(!part.length){
    //     //console.log(part);
    //   }
    // }
  }
}

module.exports = HomeController;
